import Vue from 'vue';
import Vuex from 'vuex';
import Request from '@/common/http/request.js'; // 请求方法
import * as utils from '@/common/comFun/utils.js'; // 自定义工具类
import TicketModule from './module/TICKET.js'; // 工单模块
import QmsModule from './module/QMS.js'; // 质量模块
import GuyueModule from './module/Guyue.js'; // 古越模块

import {
	HubConnectionBuilder,
	LogLevel
} from '@/uni_modules/Lyuan-SignalR/js_sdk/signalr.js'; // signalr通讯
Vue.use(Vuex);

const store = new Vuex.Store({
	state: {
		systemConfig: { // 基础应用数据
			// 是否登录 -- 用于控制消息提示是否提醒
			isLogin: false,
			// 系统信息
			sysDeviceInfo: !utils.isEmpty(uni.getStorageSync('sysDeviceInfo')) ? JSON.parse(uni.getStorageSync(
				'sysDeviceInfo')) : {},
			// 开启检索更新后，无更新时是否提示。
			UpdateSwitch: false,
			// 更新弹层是否打开
			UpdatePopupIsOpen: false,
			// 消息配置
			msgConfig: {
				activeCtx: null, // 全局消息悬浮按钮实例对象
				openMsgBtnType: true, // 全局消息按钮是否开启
				msgNum: 0, // 未读消息数量
				// openMsgBtnType: String(uni.getStorageSync('openMsgBtnType')) || 'true', // 全局消息按钮是否开启
				msgBtnIsHide: false, // 页面控制按钮是否隐藏
				hasMsg: false, // 判断是否有新的消息
				mainImage: '/static/image/Img/msg.png', // 消息按钮图标
			},
			netWorkinfo: { // 当前网络状态
				netWorkType: "unknown",
				isConnected: true
			}
		},
		// 应用参数信息
		appConfigInfo: {
			// 设备授权信息
			Authorization_Info: uni.getStorageSync('Authorization_Info') ? JSON.parse(uni.getStorageSync(
				'Authorization_Info')) : {},
			// 关闭到指定位置的页面栈层级
			routePageCurrent: 1,
			// 选中的套餐信息
			selectedComboInfo: uni.getStorageSync('selectedComboInfo') ? JSON.parse(uni.getStorageSync(
				'selectedComboInfo')) : {},
			// 历史模块记录
			ActiveModule: null,
			ActiveModuleStartType: uni.getStorageSync("ActiveModuleStartType") ?
				JSON.parse(uni.getStorageSync("ActiveModuleStartType")) : true,
			// 新 菜单模块数据信息
			ModuleInfo_All: uni.getStorageSync('ModuleInfo_All') ? JSON.parse(uni.getStorageSync(
				'ModuleInfo_All')) : [],
			// 新 提取的底部栏数据
			Module_Tabbar: uni.getStorageSync('Module_Tabbar') ? JSON.parse(uni.getStorageSync(
				'Module_Tabbar')) : [],
			// 经过过滤的数据，
			filterUnPermissionConfig: [],
			// 配置页面需要被隐藏的按钮
			unPermissionConfig: [],
			// 选中的模块菜单数据
			APPModules: {},
		},
		// 跳转表单--数据
		MenuDetail: {},
		// 列表、表单配置
		st_comPageConfig: {
			// 审批待办-默认关闭
			approveWaitToOpenNext: uni.getStorageSync('approveWaitToOpenNext') ? JSON.parse(uni.getStorageSync(
				'approveWaitToOpenNext')) : false,
			// 查阅审批流
			showListApprove: false,
			// 显示审批单据弹层
			showFormApprove: false,
			// 显示单选弹层--用于审批流
			showGlobalPopup: false,
			// 审批配置流程
			approvalConfig: {},
			// 非固定式审批流
			approveObj: {
				"tableId": 1,
				"workFlowVersionId": "",
				"workFlowDef": {
					"name": '',
					"publicFlag": 1,
					"sortNo": 1,
					"duplicateRemovelFlag": 1,
					"optionTip": "",
					"optionNotNull": 0,
					"status": 1
				},
				"directorMaxLevel": 10,
				"flowPermission": [],
				"nodeConfig": {
					"pkId": "sid-start-node",
					"nodeName": "发起人",
					"type": 0,
					"priorityLevel": "",
					"settype": "",
					"selectMode": "",
					"selectRange": "",
					"examineRoleId": "",
					"directorLevel": "",
					"replaceByUp": "",
					"examineMode": "",
					"noHanderAction": "",
					"examineEndType": "",
					"examineEndRoleId": "",
					"examineEndDirectorLevel": "",
					"ccSelfSelectFlag": "",
					"conditionList": [],
					"nodeUserList": [],
					"childNode": undefined,
					"nodeUserList": []
				}
			}
		},
		// 工单所需数据
		st_ticket: {
			// 公司报工类型
			FCJType: uni.getStorageSync('FCJType') ? uni.getStorageSync('FCJType') : null,

		},
		// 记录跳转到筛选页面，需要的参数
		BaseScreenParm: {},
		BaseScreenParmByTree: {},
		SelectPickerSetting: {},
		ImportPickerSetting: {},
		UserInfo: uni.getStorageSync('UserInfo') ? JSON.parse(uni.getStorageSync('UserInfo')) : {},
		CurrModuleID: null,
		connection: null,
		messages: [],

		SignalRConnect: null,
		IPModel: {
			// SignalR: '127.0.0.1', // SignalR
			SignalR_Status: false, // 连接状态
			SignalR_StatusInfo: {}, // 连接状态
		},
		SignalRClientID: null,
		SignalRLiveMethod: '',
	},
	mutations: {
		/** 修改state 数据_测试
		 * 	payload.Name1 - state层级属性数据 如 user.info.score
		 * 	payload.data  - 赋值内容
		 *  payload.StorageName  - 缓存名称，有缓存时会开启缓存
		 *  payload.StorageData  - 缓存内容，已处理成JSON格式
		 * 	@param {object} payload  这是一个对象，包含属性名，赋值内容，缓存名、缓存内容
		 */
		ChangeAndSetStateData(state, payload) {
			// 解构出要修改的属性名
			const {
				Name1,
				data,
				StorageName,
				StorageData,
			} = payload;

			// 如果属性名存在多级，可以使用动态属性名来修改对应的值
			const levels = Name1.split('.');
			let currentState = state;
			for (let i = 0; i < levels.length - 1; i++) {
				currentState = currentState[levels[i]];
			}
			currentState[levels[levels.length - 1]] = data;

			// 根据StorageName参数来决定是否记录缓存
			if (StorageName) {
				uni.setStorageSync(StorageName, StorageData);
			}
		},
		AddSignalRLive(state, liveMethod) {
			if (state.SignalRLiveMethod) {
				clearInterval(state.SignalRLiveMethod);
			}
			state.SignalRLiveMethod = liveMethod;
			//state.SignalRLiveMethod();
		},

		SET_CONNECTION(state, connection) {
			state.connection = connection;
		},
		ADD_MESSAGE(state, message) {
			state.messages.push(message);
		},



		// 获取当前配置模块，需要禁用的数据
		GetUnPermissionConfigInfo(state, connection) {
			let filterData = state.appConfigInfo.unPermissionConfig.filter(item => {
				return item.ModuleName == connection.moduleName
			});

			state.appConfigInfo.filterUnPermissionConfig = filterData;
		},
	},
	actions: {
		pushMsgByLocal() { // 本地发送，搭配signalR使用
			// #ifndef APP-IOS
			plus.push.createMessage("消息推送来了", null, {
				sound: 'system',
				delay: 1
			})

			// #endif


			// #ifdef APP-IOS


			// #endif
		},
		connect({
			commit,
			dispatch,
			state
		}, {
			urlBuilder
		}) {

			const connection = new HubConnectionBuilder()
				.withUrl(urlBuilder)
				.configureLogging(LogLevel.Trace)
				.build();

			// console.log(urlBuilder)

			commit('ChangeAndSetStateData', {
				Name1: 'SignalRConnect',
				data: connection
			});

			connection.onclose(() => {
				setTimeout(() => {
					dispatch('connect', {
						urlBuilder
					}); // 重新连接  
				}, 5000);
			});

			// try {
			// 发起连接
			connection.start().then(function() {
				// console.log(state.UserInfo.UserID)


				let SignalRKey = {
					oldKey: uni.getStorageSync('LocalMsgKey'),
					newKey: '',
				}

				// 参数：(连接字段，账套ID，机器码)
				let deviceID = state.systemConfig.sysDeviceInfo.deviceId;
				connection.invoke("ConnectByMachineNo", +state.UserInfo.Business, +state.UserInfo
						.UserID,
						deviceID)
					.catch(
						function(err) {
							console.log(err)
						});


				// 查看连接状态
				connection.on("onConnect", (data) => {
					let backData = JSON.parse(data);
					let connetType = false;
					if (backData.Status == 200) {
						connetType = true;

						SignalRKey.newKey = data.Data;
						// 记录signalR连接的kay
						uni.setStorageSync('LocalMsgKey', data.Data);
					} else if (backData.Status == 500) {
						connetType = false;
					}

					commit('ChangeAndSetStateData', {
						Name1: 'IPModel.SignalR_Status',
						data: connetType
					});

					commit('ChangeAndSetStateData', {
						Name1: 'SignalRClientID',
						data: data
					});



					// 接收数据

					connection.on("onReceiveMSG", (ret) => {
						// console.log(ret);
						// 增加判断条件，控制消息提示
						if (state.systemConfig.isLogin) {
							let data = JSON.parse(ret);
							if (data.Status == 200) {
								// console.log(data);
								//  提示接收到消息， 
								let theType = state.systemConfig.msgConfig
									.openMsgBtnType == true;
								commit('ChangeAndSetStateData', {
									Name1: 'systemConfig.msgConfig.hasMsg',
									data: theType
								});
								commit('ChangeAndSetStateData', {
									Name1: 'systemConfig.msgConfig.msgNum',
									data: state.systemConfig.msgConfig.msgNum +
										1
								});
								dispatch('pushMsgByLocal')
							}
						}
					})
				});

			}).catch(function(err) {
				commit('ChangeAndSetStateData', {
					Name1: 'IPModel.SignalR_Status',
					data: false
				});
				//5s断线重连
				setTimeout(() => {
					dispatch('connect', {
						urlBuilder
					});
				}, 5000);

			});;



			// } catch (error) {
			// 	console.error('Failed to start connection:', error);
			// 	setTimeout(() => {
			// 		dispatch('connect', {
			// 			urlBuilder
			// 		}); // 重新连接  
			// 	}, 5000);
			// }
		},
		// disconnect({
		// 	commit,
		// 	state
		// }) {
		// 	if (state.connection && state.connection.state === signalR.HubConnectionState.Connected) {
		// 		state.connection.stop().catch(err => console.error(err.toString()));
		// 		commit('SET_CONNECTION', null);
		// 	}
		// },
		// sendMessage({
		// 	state
		// }, message) {
		// 	if (state.connection && state.connection.state === signalR.HubConnectionState.Connected) {
		// 		state.connection.invoke("SendMessage", message).catch(err => console.error(err.toString()));
		// 	}
		// },

		GetMessageInfo({
			commit,
			dispatch,
			state
		}, {
			FEDate,
			Sender,
			ModuleName,
			FBDate,
		}) { // 获取消息详情
			return Request.PromiseRequest('GetSYSMessageList', {
				UserID: state.UserInfo.UserID,
				FEDate: FEDate,
				Sender: Sender,
				ModuleName: ModuleName,
				FBDate: FBDate,
			}).promise;

		},
		GetAPPRoleColFunByRoleID({
			commit,
			dispatch,
			state
		}, {
			moduleName,
			moduleType
		}) { // 根据APP表单名称获取所属权限

			let promise = Request.PromiseRequest('getAPPRoleColFunByRoleID', {
				moduleName: moduleName,
				moduleType: moduleType,
			}).promise;
			return promise;

		},
	},
	getters: {
		GetFCJType: state => { // 获取公司报工类型
			return state.st_ticket.FCJType
		},
		UserInfo: state => state.UserInfo,
	},
	modules: { // 可以添加更多的模块
		QmsModule: QmsModule, // 将主题模块添加为名为"QmsModule"的模块
		TicketModule: TicketModule,
		GuyueModule: GuyueModule,
	}
})

export default store